//
//  NSDate+Extension.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/11.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import Foundation

extension NSDate {
    
    class func sinaDate(string: String?) -> NSDate? {
        
        if string == nil {
            return nil
        }
        
        let dt = YYDateFormatter.sharedFormatter
        //制定时间格式化字符串
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //将字符串转成 NSDate
        let result = dt.dateFromString(string!)
        return result
    }
    
    //返回新浪微博的字符串
    var sinaDescription: String? {
        
        let dt = YYDateFormatter.sharedFormatter
        
        //取到当前的时间对象
        let calendar = NSCalendar.currentCalendar()
        //当前时间
        let currentDate = NSDate()
        
        if isDateThisYear(self) {
            //判断是否是今天
            if calendar.isDateInToday(self){
                //返回的结果是秒数
                let result = currentDate.timeIntervalSinceDate(self)
                //小于60秒就是刚刚,小于一个小时就是多少分钟前
                
                if result < 60 {
                    return "刚刚"
                }else if result < 60 * 60 {
                    return "\(Int(result/60))分钟前"
                }else {
                    return "\(Int(result/60/60))小时前"
                }
            }else if calendar.isDateInYesterday(self) {
                dt.dateFormat = "昨天 HH:mm"
            }else{
                dt.dateFormat = "MM-dd HH:mm"
            }
        }else{
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        return dt.stringFromDate(self)
    }
    
    //判断当前时间是否是同一年
    private func isDateThisYear(date: NSDate) -> Bool{
        let nowDate = NSDate()
        
        let df = YYDateFormatter.sharedFormatter
        df.locale = NSLocale(localeIdentifier: "en_US")
        df.dateFormat = "yyyy"
        
        //传入时间的年份
        let dateStr = df.stringFromDate(date)
        //当前时间的年份
        let nowDateStr = df.stringFromDate(nowDate)
        
        return (dateStr as NSString).isEqualToString(nowDateStr)
    }
}